﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Linq;

namespace SimpleDesktop
{
    public class ClassPage: TabPage
    {
        public ListView listView {  get; set; }
        private ImageList imageList = new ImageList();
        private void initalize()
        {
            listView = new ListView();
            imageList.ImageSize = new Size(64, 64); // 设置图标大小
            listView.LargeImageList = imageList;
            listView.Dock = DockStyle.Fill;
            listView.ItemActivate += listView_ItemActivate;
            listView.DragDrop += listView_DragDrop;
            listView.DragEnter += listView_DragEnter;
            listView.ItemDrag += ListView_ItemDrag;
            listView.AllowDrop = true;

            initializeMenu(listView);

            Controls.Add(listView);
        }


        public ClassPage(string name)
        {
            initalize();
            Text = name;
        }
        public ClassPage()
        {
            initalize();
            Text = "ClassPage";
        }

        private void initializeMenu(ListView listView)
        {
            // 初始化右键的菜单
            ContextMenuStrip contextMenuStrip = new ContextMenuStrip();
            ToolStripMenuItem deleteMenuItem = new ToolStripMenuItem("删除当前快捷方式");
            deleteMenuItem.Click += (sender, e) =>
            {
                if (listView.SelectedItems.Count > 0)
                {
                    foreach (ListViewItem item in listView.SelectedItems)
                    {
                        listView.Items.Remove(item);
                    }
                }
            };
            contextMenuStrip.Items.Add(deleteMenuItem);

            // TabControl的MouseClick事件，以显示右键菜单
            listView.MouseClick += (sender, e) =>
            {
                if (e.Button == MouseButtons.Right)
                {
                    contextMenuStrip.Show(listView, e.Location);
                }
            };

            listView.KeyDown += (sender, e) =>
            {
                if (e.KeyCode == Keys.Delete)
                {
                    if (listView.SelectedItems.Count > 0)
                    {
                        foreach (ListViewItem item in listView.SelectedItems)
                        {
                            listView.Items.Remove(item);
                        }
                    }
                }
            };

        }

        /**
         * 在窗体中显示相应的图标
         * @param path 快捷方式路径
         * 
         * 更新：如果文件后缀名为.lnk，那么自动去掉
         */
        public void addPicture(string path)
        {
            if (!File.Exists(path)) return;  // 如果路径不存在
            Icon shortcutIcon = Icon.ExtractAssociatedIcon(path);
            string shortcutName = Path.GetFileName(path);
            if (shortcutName.EndsWith(".lnk")) shortcutName = Path.GetFileNameWithoutExtension(path);
            // 将图标添加到ImageList
            imageList.Images.Add(shortcutName, shortcutIcon);
            // 创建ListViewItem并设置其图标和文本
            ListViewItem item = new ListViewItem(shortcutName);
            item.ImageKey = shortcutName;
            item.Tag = path; // 将快捷方式路径存储在Tag属性中
            // 将ListViewItem添加到ListView
            listView.Items.Add(item);
        }


        /**
         * 打开应用程序
         * @param path 应用程序路径
         */
        private void activateProgram(string path)
        {
            if (path != null && File.Exists(path))
            {
                try
                {
                    // 启动应用程序
                    ProcessStartInfo startInfo = new ProcessStartInfo();
                    startInfo.FileName = "cmd"; // 指定要启动的程序，这里是命令提示符
                    startInfo.Arguments = "/C \"" +path+"\""; // 指定要传递给程序的命令行参数，这里是执行 'dir' 命令
                    startInfo.RedirectStandardOutput = true; // 重定向标准输出，以便读取命令行的输出
                    startInfo.UseShellExecute = false; // 设置为 false 以使用重定向
                    startInfo.CreateNoWindow = true; // 设置为 true 以隐藏命令提示符窗口
                    Process.Start(startInfo);
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"Failed to open shortcut: {ex.Message}");
                }
            }
        }

        private void listView_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                e.Effect = DragDropEffects.Copy;
            }
            else
            {
                e.Effect = DragDropEffects.Move;
            }
        }

        private void listView_DragDrop(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
                foreach (string file in files)
                {
                    addPicture(file);
                }
            }
            else
            {
                // 拖动代码
                // 获取拖动到的位置
                Point point = listView.PointToClient(new Point(e.X, e.Y));
                ListViewItem? targetItem = listView.FindNearestItem(SearchDirectionHint.Right, point);
                ListViewItem draggedItem = (ListViewItem)e.Data.GetData(typeof(ListViewItem));
                if (targetItem != null)
                {
                    // 获取源项目
                    List<ListViewItem> list = new List<ListViewItem>();
                    foreach (ListViewItem item in listView.Items)
                    {
                        if (item == targetItem)
                        {
                            list.Add(draggedItem);
                        }
                        if (item == draggedItem) continue;
                        list.Add(item);
                    }
                    listView.Items.Clear();

                    // 移动项目
                    foreach (ListViewItem item in list)
                    {
                        listView.Items.Add(item);
                    }
                }
                else
                {
                    // 如果没有目标项目（例如拖动到空白区域），则将项目插入到最后
                    listView.Items.Remove(draggedItem);
                    listView.Items.Add(draggedItem);
                }
            }
        }


        private void listView_ItemActivate(object sender, EventArgs e)
        {
            if (listView.SelectedItems.Count > 0)
            {
                ListViewItem item = listView.SelectedItems[0];
                string shortcutPath = item.Tag as string;
                activateProgram(shortcutPath);
            }
        }

        private void ListView_ItemDrag(object sender, ItemDragEventArgs e)
        {
            listView.DoDragDrop(e.Item, DragDropEffects.Move);
        }
    }
}
